package org.jeecg.modules.haili.utils;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.modules.haili.config.InsuranceConfigProperties;
import org.jeecg.modules.haili.entity.request.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 发送报文，接收相应的信使
 */
@Service
public class Messenger {
    private Logger logger = LoggerFactory.getLogger(Messenger.class);

    @Autowired
    private InsuranceConfigProperties insuranceConfigProperties;

    public String sendMessage(Message message) {
        String resp = null;
        HttpURLConnection connection = null;
        try {
            String messagePackt = JSONObject.toJSONString(message);
            logger.info("请求报文{}", messagePackt);
            URL url = new URL(insuranceConfigProperties.getServerUrl()); //url地址

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();

            try (OutputStream os = connection.getOutputStream()) {
                os.write(messagePackt.getBytes("UTF-8"));
            }

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                String lines;
                StringBuffer sbf = new StringBuffer();
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sbf.append(lines);
                }
                logger.info("返回报文：" + sbf.toString());
                resp = sbf.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null)
                connection.disconnect();
        }
        return resp;
    }
}
